package com.romin.action;

import com.romin.dao.AdvertisementDao;
import com.romin.dao.ArticleDao;
import com.romin.pojo.Advertisement;
import com.romin.pojo.Article;
import com.romin.pojo.ResponseBean;
import org.jboss.logging.annotations.Param;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;

/**
 * @author cloud.eve
 */
@Controller
public class ArticleAction {
    @Resource
    public ArticleDao articleDao;
    @Resource
    public AdvertisementDao advertisementDao;

    @RequestMapping("/admin/views/articleManager")
    public String userManager(Model model) {
        Iterable<Article> articles = articleDao.findAll();
        Iterable<Advertisement> advertisements = advertisementDao.findAll();
        model.addAttribute("articles", articles);
        model.addAttribute("advertisements", advertisements);
        return "views/articleManager";
    }

    @RequestMapping("/admin/articleDetail/{id}")
    public String articleDetail(@PathVariable long id,Model model) {
        Article article = articleDao.findOne(id);
        model.addAttribute("article",article);
        return "views/articleDetail";
    }

    @RequestMapping(value = "/admin/articleUpdate",method = RequestMethod.POST)
    @ResponseBody
    public String updateuserManager(@Param Article article) {
        Article originArticle = null;
        boolean editFlag = false;
        if (article.getId() != null) {
            originArticle = articleDao.findOne(article.getId());
        }else{
            originArticle = new Article();
        }
        if(article.getTitle()!=null){
            editFlag = true;
            originArticle.setTitle(article.getTitle());
        }
        if(article.getContent()!=null){
            editFlag = true;
            originArticle.setContent(article.getContent());
        }
        if(article.getAdsLocation()!=null){
            editFlag = true;
            originArticle.setAdsLocation(article.getAdsLocation());
        }
        if(article.getAdvertisement()!=null&&article.getAdvertisement().getId()!=0){
            editFlag = true;
            originArticle.setAdvertisement(advertisementDao.findOne(article.getAdvertisement().getId()));
        }

        boolean result = false;
        try {
            if (editFlag) {
                articleDao.save(originArticle);
                System.out.println(article.getTitle());
                System.out.println(article.getContent());
                result = true;
            }
        } catch (Exception e) {
        }
        return new ResponseBean(result).build();
    }


}
